<template>
  <MainLayout current-page="home">
    <!-- 首页内容：AI模型选择网格 -->
    <div class="max-w-5xl mx-auto p-6 min-h-screen flex flex-col">
      
      <!-- 首页模式：AI模型选择 -->
      <div class="flex-1 flex flex-col">
        <!-- 顶部导航 -->
        <div class="h-16 flex items-center justify-center px-8 bg-gradient-to-r from-white via-gray-50 to-white rounded-xl shadow-sm border border-gray-100 mb-6">
          <nav class="flex items-center space-x-10">
            <a 
              href="#" 
              @click="setActiveTab('all')"
              :class="[
                'font-medium relative group transition-colors',
                activeTab === 'all' 
                  ? 'text-primary font-bold' 
                  : 'text-gray-600 hover:text-gray-900'
              ]"
            >
              <span class="relative z-10">所有AI学习模型</span>
              <span 
                v-if="activeTab === 'all'"
                class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform origin-left transition-all duration-300 ease-out"
              ></span>
              <span 
                v-else
                class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform scale-x-0 origin-left transition-all duration-300 ease-out group-hover:scale-x-100"
              ></span>
            </a>
            <a 
              href="#" 
              @click="setActiveTab('math')"
              :class="[
                'font-medium relative group transition-colors',
                activeTab === 'math' 
                  ? 'text-primary font-bold' 
                  : 'text-gray-600 hover:text-gray-900'
              ]"
            >
              <span class="relative z-10">AI学数学</span>
              <span 
                v-if="activeTab === 'math'"
                class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform origin-left transition-all duration-300 ease-out"
              ></span>
              <span 
                v-else
                class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform scale-x-0 origin-left transition-all duration-300 ease-out group-hover:scale-x-100"
              ></span>
            </a>
            <a 
              href="#" 
              @click="setActiveTab('english')"
              :class="[
                'font-medium relative group transition-colors',
                activeTab === 'english' 
                  ? 'text-primary font-bold' 
                  : 'text-gray-600 hover:text-gray-900'
              ]"
            >
              <span class="relative z-10">AI学英语</span>
              <span 
                v-if="activeTab === 'english'"
                class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform origin-left transition-all duration-300 ease-out"
              ></span>
              <span 
                v-else
                class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform scale-x-0 origin-left transition-all duration-300 ease-out group-hover:scale-x-100"
              ></span>
            </a>
            <a 
              href="#" 
              @click="setActiveTab('chinese')"
              :class="[
                'font-medium relative group transition-colors',
                activeTab === 'chinese' 
                  ? 'text-primary font-bold' 
                  : 'text-gray-600 hover:text-gray-900'
              ]"
            >
              <span class="relative z-10">AI学语文</span>
              <span 
                v-if="activeTab === 'chinese'"
                class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform origin-left transition-all duration-300 ease-out"
              ></span>
              <span 
                v-else
                class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform scale-x-0 origin-left transition-all duration-300 ease-out group-hover:scale-x-100"
              ></span>
            </a>
            <a 
              href="#" 
              @click="setActiveTab('program')"
              :class="[
                'font-medium relative group transition-colors',
                activeTab === 'program' 
                  ? 'text-primary font-bold' 
                  : 'text-gray-600 hover:text-gray-900'
              ]"
            >
              <span class="relative z-10">AI学编程</span>
              <span 
                v-if="activeTab === 'program'"
                class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform origin-left transition-all duration-300 ease-out"
              ></span>
              <span 
                v-else
                class="absolute inset-x-0 -bottom-1 h-[3px] bg-primary/90 rounded-full transform scale-x-0 origin-left transition-all duration-300 ease-out group-hover:scale-x-100"
              ></span>
            </a>
          </nav>
        </div>

        <!-- AI模型卡片网格 -->
        <div class="grid grid-cols-4 gap-4 mb-8">
          <div
            v-for="model in filteredModels"
            :key="model.id"
            @click="selectModel(model.id)"
            @mouseenter="handleMouseEnter(model.id)"
            @mouseleave="handleMouseLeave(model.id)"
            :class="[
              'bg-white p-2.5 rounded-lg border cursor-pointer transition-all relative',
              model.selected ? 'border-primary shadow-md' : 'border-gray-200 hover:border-primary/30 hover:shadow-md'
            ]"
          >
            <!-- 免费信息
            <div v-if="model.free"  class="absolute top-0 right-0 text-xs bg-red-100 px-1 rounded-lg pl-2 pr-2 pt-1 pb-1" style="font-size:13px">
              {{ '免费'}}
            </div> -->
            
            
            <div class="flex items-start space-x-2">
              <div :class="['w-6 h-6 rounded-lg flex items-center justify-center flex-shrink-0', model.colorClass]">
                <i :class="[model.iconClass, 'text-sm']"></i>
              </div>
              <div class="flex-1 min-w-0">
                <div class="font-medium text-sm">{{ model.displayName }}</div>
                <div v-if="model.selected" class="absolute top-0 right-0 bg-green-200 px-1 rounded-tr-lg pl-2 pr-2 pt-1 pb-1 text-xs text-primary" style="font-size:12px; color: black; font-weight: bold;">已选</div>
                <!--<div class="absolute bottom-0 right-0 bg-green-200 px-1 rounded-br-lg pl-2 pr-2 pt-1 pb-1 text-xs text-primary" style="font-size:12px; color: black; font-weight: bold;">已选</div>-->
              </div>
            </div>
            
            <!-- 模型标签显示 -->
            <div v-if="model.tags && model.tags.length > 0" class="mt-2 flex flex-wrap gap-1">
              <span 
                v-for="tag in model.tags.slice(0, 2)" 
                :key="tag.id"
                :style="{ backgroundColor: tag.color + '20', color: tag.color }"
                class="text-xs px-2 py-1 rounded-full font-medium"
              >
                {{ tag.name }}
              </span>
              <span 
                v-if="model.tags.length > 2"
                class="text-xs text-gray-500 px-2 py-1"
              >
                +{{ model.tags.length - 2 }}
              </span>
            </div>
            
            <!-- 详细模型信息弹出框 -->
            <div 
              v-if="isModelHovered(model.id)"
              @mouseenter="handlePopupMouseEnter"
              @mouseleave="handlePopupMouseLeave"
              @click.stop
              class="absolute top-full left-0 mt-2 w-80 bg-white rounded-lg shadow-xl border border-gray-200 z-50"
            >
              <!-- 弹出框内容 -->
              <div class="p-4">
                <!-- 头部信息 -->
                <div class="flex items-center mb-3">
                  <div :class="['w-8 h-8 rounded-lg flex items-center justify-center mr-3', model.colorClass]">
                    <i :class="[model.iconClass, 'text-sm']"></i>
                  </div>
                  <div>
                    <div class="font-semibold text-lg text-gray-800">{{ model.name }}</div>
                  </div>
                </div>
                
                <!-- 模型简介 -->
                <div class="mb-4">
                  <div class="flex items-center justify-between mb-3">
                    <span class="font-medium text-gray-800">模型简介</span>
                    <button 
                      @click.stop="viewModelDetails(model.modelKey)"
                      class="text-blue-500 text-sm hover:text-blue-600 hover:underline"
                    >
                      查看详情 >
                    </button>
                  </div>
                  
                  <div class="text-sm text-gray-600 leading-relaxed">
                    {{ getModelDescription(model.modelKey) }}
                  </div>
                </div>
                
                <!-- 模型标签 -->
                <div v-if="model.tags && model.tags.length > 0" class="mb-4">
                  <div class="mb-2">
                    <span class="font-medium text-gray-800">模型标签</span>
                  </div>
                  <div class="flex flex-wrap gap-2">
                    <span 
                      v-for="tag in model.tags" 
                      :key="tag.id"
                      :style="{ 
                        backgroundColor: tag.color + '20', 
                        color: tag.color,
                        borderColor: tag.color + '40'
                      }"
                      class="text-xs px-3 py-1 rounded-full font-medium border"
                    >
                      <i :class="[tag.iconClass, 'mr-1']"></i>
                      {{ tag.name }}
                    </span>
                  </div>
                </div>
                
                <!-- 用户口碑 
                <div class="mb-4">
                  <div class="mb-3">
                    <span class="font-medium text-gray-800">用户口碑</span>
                  </div>
                  
                  <div class="space-y-2">
                    <div class="flex items-center justify-between">
                      <span class="text-sm text-gray-600">响应速度</span>
                      <div class="flex items-center">
                        <div class="flex items-center mr-2" v-html="generateStarRating(getModelDetails(model.modelKey).ratings.responseSpeed.score)"></div>
                        <span class="text-sm font-medium text-gray-800">{{ getModelDetails(model.modelKey).ratings.responseSpeed.score }}分</span>
                      </div>
                    </div>
                    
                    <div class="flex items-center justify-between">
                      <span class="text-sm text-gray-600">回答准确度</span>
                      <div class="flex items-center">
                        <div class="flex items-center mr-2" v-html="generateStarRating(getModelDetails(model.modelKey).ratings.accuracy.score)"></div>
                        <span class="text-sm font-medium text-gray-800">{{ getModelDetails(model.modelKey).ratings.accuracy.score }}分</span>
                      </div>
                    </div>
                    
                    <div class="flex items-center justify-between">
                      <span class="text-sm text-gray-600">文案能力</span>
                      <div class="flex items-center">
                        <div class="flex items-center mr-2" v-html="generateStarRating(getModelDetails(model.modelKey).ratings.copywriting.score)"></div>
                        <span class="text-sm font-medium text-gray-800">{{ getModelDetails(model.modelKey).ratings.copywriting.score }}分</span>
                      </div>
                    </div>
                    
                    <div class="flex items-center justify-between">
                      <span class="text-sm text-gray-600">绘画能力</span>
                      <div class="flex items-center">
                        <div class="flex items-center mr-2" v-html="generateStarRating(getModelDetails(model.modelKey).ratings.drawing.score)"></div>
                        <span class="text-sm font-medium text-gray-800">{{ getModelDetails(model.modelKey).ratings.drawing.score }}分</span>
                      </div>
                    </div>
                    
                    <div class="flex items-center justify-between">
                      <span class="text-sm text-gray-600">编程能力</span>
                      <div class="flex items-center">
                        <div class="flex items-center mr-2" v-html="generateStarRating(getModelDetails(model.modelKey).ratings.programming.score)"></div>
                        <span class="text-sm font-medium text-gray-800">{{ getModelDetails(model.modelKey).ratings.programming.score }}分</span>
                      </div>
                    </div>
                  </div>
                </div>
                -->

              </div>
            </div>
          </div>
        </div>

        <!-- 底部输入区域 -->
        <div class="mt-auto bg-white rounded-2xl border border-gray-200 p-6">
          <div class="relative">
            <textarea 
              v-model="userInput"
              class="w-full border-none bg-gray-50/70 rounded-2xl pl-6 pr-32 py-5 resize-none focus:ring-2 focus:ring-primary focus:outline-none text-base" 
              rows="3" 
              placeholder="请输入问题（提示：输入后可快速生成AI回答，支持截图粘贴、图片/文件上传）"
            ></textarea>
            <div class="absolute right-4 bottom-4 flex items-center space-x-2">
              <button @click="handleMicrophone" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                <i class="fas fa-microphone"></i>
              </button>
              <button @click="handleUpload" class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-300">
                <i class="fas fa-paperclip"></i>
              </button>
              <button @click="enterChatMode" class="w-8 h-8 rounded-full bg-primary text-white flex items-center justify-center hover:bg-primary/90">
                <i class="fas fa-paper-plane"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import MainLayout from '@/components/layout/MainLayout.vue'
import { 
  getModelDisplayConfig, 
  getModelDisplayName, 
  generateStarRating
} from '@/utils/chatUtils'
import type { AiModel } from '@/types/chat'

const router = useRouter()

const userInput = ref('')
const aiModels = ref<AiModel[]>([])
const activeTab = ref('all')
const groupedData = ref<any>(null)

// 计算属性：根据当前选中的标签过滤模型
const filteredModels = computed(() => {
  if (!groupedData.value) {
    return aiModels.value
  }
  
  let models = []
  if (activeTab.value === 'all') {
    models = groupedData.value.allModels || []
  } else {
    models = groupedData.value.groupedModels[activeTab.value] || []
  }
  
  // 确保每个模型都有正确的free字段映射
  return models.map((model: any) => ({
    ...model,
    free: Boolean(model.isFree), // 确保转换为布尔值
    name: model.displayName || model.name,
    modelKey: model.modelKey || model.name
  }))
})

// 设置活动标签
const setActiveTab = (tab: string) => {
  activeTab.value = tab
  
  // 切换标签时取消选中所有模型
  clearAllSelectedModels()
}

// 新增：清除所有模型的选择状态
const clearAllSelectedModels = () => {
  // 清除 filteredModels 中的选择状态
  filteredModels.value.forEach(model => {
    model.selected = false
  })
  
  // 清除 aiModels 中的选择状态
  aiModels.value.forEach(model => {
    model.selected = false
  })
  
  // 清除 groupedData 中的所有选择状态
  if (groupedData.value) {
    // 清除 allModels 中的选择状态
    if (groupedData.value.allModels) {
      groupedData.value.allModels.forEach(model => {
        model.selected = false
      })
    }
    
    // 清除所有标签分组中的选择状态
    Object.keys(groupedData.value.groupedModels).forEach(tagKey => {
      const tagModels = groupedData.value.groupedModels[tagKey]
      if (tagModels) {
        tagModels.forEach(model => {
          model.selected = false
        })
      }
    })
  }
}

// 获取AI模型数据 - 修改为获取分组数据
const fetchAiModels = async () => {
  try {
    const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'
    const response = await fetch(`${baseURL}/ai-models/active`)
    
    if (response.ok) {
      const result = await response.json()
      if (result.success) {
        groupedData.value = result.data
        
        // 设置所有模型（用于兼容性）
        aiModels.value = (result.data.allModels || []).map((model: any) => {
          return {
            id: model.id,
            name: model.displayName,
            modelKey: model.modelKey,
            icon: model.icon,
            iconClass: model.iconClass || 'fas fa-robot',
            colorClass: model.colorClass || 'bg-gray-100 text-gray-600',
            selected: false,
            free: Boolean(model.isFree), // 确保转换为布尔值
            modelDescription: model.modelDescription,
            rankPosition: model.rankPosition,
            flowersCount: model.flowersCount,
            eggsCount: model.eggsCount,
            popularityScore: model.popularityScore,
            discussionsCount: model.discussionsCount,
            responseSpeedScore: model.responseSpeedScore,
            accuracyScore: model.accuracyScore,
            copywritingScore: model.copywritingScore,
            drawingScore: model.drawingScore,
            programmingScore: model.programmingScore,
            tags: model.tags || [] // 添加标签信息
          }
        })
        
        console.log('AI模型数据加载成功:', aiModels.value)
        console.log('免费模型数量:', aiModels.value.filter(m => m.free).length)
        console.log('免费模型列表:', aiModels.value.filter(m => m.free).map(m => m.name))
        console.log('分组数据:', groupedData.value)
      } else {
        ElMessage.error('获取AI模型失败: ' + result.message)
      }
    } else {
      ElMessage.error('获取AI模型失败')
    }
  } catch (error) {
    console.error('获取AI模型错误:', error)
    ElMessage.error('网络错误，请重试')
    aiModels.value = getDefaultModels()
  }
}

// 获取默认模型数据（备用方案）
const getDefaultModels = (): AiModel[] => {
  return [
    { id: 1, name: 'Grok-4', modelKey: 'Grok-4', icon: 'G', iconClass: 'fas fa-robot', colorClass: 'bg-blue-100 text-blue-600', selected: false, free: false },
    { id: 2, name: 'AskAgents', modelKey: 'AskAgents', icon: 'A', iconClass: 'fas fa-brain', colorClass: 'bg-purple-100 text-purple-600', selected: false, free: false },
    { id: 3, name: 'DeepSeek-R1', modelKey: 'deepseek-reasoner', icon: 'D', iconClass: 'fas fa-wand-magic-sparkles', colorClass: 'bg-orange-100 text-orange-600', selected: false, free: true },
    { id: 5, name: 'Gemini-2.5-Flash', modelKey: 'Gemini-2.5-Flash', icon: 'G', iconClass: 'fas fa-sparkles', colorClass: 'bg-green-100 text-green-600', selected: false, free: true },
    { id: 6, name: 'DeepSeek-R1联网版', modelKey: 'DeepSeek-R1_Internet', icon: 'D', iconClass: 'fas fa-globe', colorClass: 'bg-orange-100 text-orange-600', selected: false, free: true },
    { id: 7, name: 'GPT-4.1 nano', modelKey: 'GPT-4.1-nano', icon: 'G', iconClass: 'fas fa-microchip', colorClass: 'bg-blue-100 text-blue-600', selected: false, free: true },
    { id: 8, name: '浮点搜索2.0', modelKey: 'Fudian-Searh', icon: '浮', iconClass: 'fas fa-search', colorClass: 'bg-yellow-100 text-yellow-600', selected: false, free: true },
    { id: 9, name: 'Gemini 2.5 Pro优惠版', modelKey: 'Gemini-2.5-Pro-youhui', icon: 'G', iconClass: 'fas fa-gem', colorClass: 'bg-green-100 text-green-600', selected: false, free: false },
    { id: 10, name: 'Gemini 2.5 Pro', modelKey: 'Gemini-2.5-Pro', icon: 'G', iconClass: 'fas fa-gem', colorClass: 'bg-green-100 text-green-600', selected: false, free: false },
    { id: 11, name: 'GPT-4.1', modelKey: 'gpt-4.1', icon: 'G', iconClass: 'fas fa-robot', colorClass: 'bg-blue-100 text-blue-600', selected: false, free: false },
    { id: 12, name: '豆包 1.5 Pro', modelKey: 'doubao-1.5-Pro', icon: '豆', iconClass: 'fas fa-seedling', colorClass: 'bg-red-100 text-red-600', selected: false, free: true },
    { id: 13, name: 'DeepSeek-V3', modelKey: 'deepseek-chat', icon: 'D', iconClass: 'fas fa-wand-magic-sparkles', colorClass: 'bg-orange-100 text-orange-600', selected: false, free: false },
    { id: 14, name: 'Claude-4-Sonnet', modelKey: 'claude-4-sonnet', icon: 'C', iconClass: 'fas fa-user-robot', colorClass: 'bg-purple-100 text-purple-600', selected: false, free: false }
  ]
}

// 模型选择函数，支持多选
const selectModel = (modelId: number) => {
  // 首先在 filteredModels 中找到模型
  const filteredModel = filteredModels.value.find(m => m.id === modelId)
  if (filteredModel) {
    // 更新 filteredModel 的选择状态
    filteredModel.selected = !filteredModel.selected
    
    // 同时更新 aiModels 中对应模型的选择状态
    const aiModel = aiModels.value.find(m => m.id === modelId)
    if (aiModel) {
      aiModel.selected = filteredModel.selected
    }
    
    // 如果是从 groupedData 来的模型，也要更新对应的选择状态
    if (groupedData.value) {
      // 更新 allModels 中的状态
      const allModel = groupedData.value.allModels?.find(m => m.id === modelId)
      if (allModel) {
        allModel.selected = filteredModel.selected
      }
      
      // 更新对应标签分组中的状态
      Object.keys(groupedData.value.groupedModels).forEach(tagKey => {
        const tagModels = groupedData.value.groupedModels[tagKey]
        const tagModel = tagModels?.find(m => m.id === modelId)
        if (tagModel) {
          tagModel.selected = filteredModel.selected
        }
      })
    }
  }
}

// 获取选中的AI模型
const getSelectedModels = () => {
  return aiModels.value.filter(model => model.selected)
}

// 生成唯一conversationId的函数
const generateConversationId = (userId: string = 'anonymous'): string => {
  const timestamp = Date.now()
  const uuid = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
  return `conv-${userId}-${timestamp}-${uuid}`
}

// 获取当前用户ID
const getCurrentUserId = (): string => {
  return localStorage.getItem('userId') || 'anonymous'
}

// 进入聊天模式 - 直接跳转到ChatView
const enterChatMode = async () => {
  const selectedModels = getSelectedModels()
  if (selectedModels.length === 0) {
    ElMessage.warning('请至少选择一个AI模型')
    return
  }
  
  if (!userInput.value.trim()) {
    ElMessage.warning('请输入问题内容')
    return
  }
  
  try {
    // 生成主conversationId
    const userId = getCurrentUserId()
    const conversationId = generateConversationId(userId)
    
    // 第一步：创建轮次占位符
    const modelIds = selectedModels.map(model => model.id)
    const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api'}/chat/create-round`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        conversationId: conversationId,
        userId: userId,
        question: userInput.value,
        modelIds: modelIds
      })
    })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    if (!result.success) {
      throw new Error(result.error || '创建轮次失败')
    }
    
    // 将轮次信息和选中的模型保存到 sessionStorage
    sessionStorage.setItem('selectedModels', JSON.stringify(selectedModels))
    sessionStorage.setItem('currentQuestion', userInput.value)
    sessionStorage.setItem('roundData', JSON.stringify(result.data))
    
    // 跳转到 ChatView 页面
    router.push(`/chat/${conversationId}`)
    
  } catch (error) {
    console.error('进入聊天模式错误:', error)
    ElMessage.error('创建对话失败，请重试')
  }
}

// 模型简介数据
const modelDescriptions = ref<{ [key: string]: string }>({
  'Grok-4': 'Grok-4是xAI开发的最新大语言模型，具有强大的推理能力和广泛的知识覆盖，特别擅长复杂问题分析和创意生成。',
  'AskAgents': 'AskAgents是一个专业的AI代理平台，提供多种专业领域的智能助手，能够处理特定行业的复杂任务。',
  'deepseek-reasoner': 'DeepSeek-R1是深度求索开发的推理模型，具备强大的逻辑推理能力，特别适合需要深度思考的复杂问题。',
  'Gemini-2.5-Flash': 'Gemini-2.5-Flash是Google开发的高效模型，在保持高质量输出的同时具有极快的响应速度，适合实时对话。',
  'DeepSeek-R1_Internet': 'DeepSeek-R1联网版在原有推理能力基础上增加了实时网络搜索功能，能够获取最新信息并进行分析。',
  'GPT-4.1-nano': 'GPT-4.1-nano是OpenAI的轻量级模型，在保持核心能力的同时优化了资源消耗，适合高频使用场景。',
  'Fudian-Searh': '浮点搜索2.0是专业的搜索增强模型，能够进行深度网络搜索和信息整合，提供准确可靠的搜索结果。',
  'Gemini-2.5-Pro-youhui': 'Gemini 2.5 Pro优惠版是Google Pro模型的优惠版本，提供专业级AI能力的同时具有更优惠的价格。',
  'Gemini-2.5-Pro': 'Gemini 2.5 Pro是Google的旗舰模型，具备强大的多模态能力和专业级分析能力，适合复杂任务处理。',
  'gpt-4.1': 'GPT-4.1是OpenAI的最新旗舰模型，在GPT-4基础上进行了全面优化，具备更强的推理能力和更广的知识覆盖。',
  'doubao-1.5-Pro': '豆包 1.5 Pro是字节跳动开发的AI模型，在中文理解和生成方面表现优异，特别适合中文场景应用。',
  'deepseek-chat': 'DeepSeek-V3是深度求索的通用对话模型，在保持高效性能的同时提供流畅的对话体验。',
  'claude-4-sonnet': 'Claude-4-Sonnet是Anthropic开发的高性能模型，以安全性和可靠性著称，特别适合需要谨慎处理的敏感任务。'
})

// 获取模型简介
const getModelDescription = (modelKey: string) => {
  const model = aiModels.value.find(m => m.modelKey === modelKey)
  if (model && model.modelDescription) {
    return model.modelDescription
  }
  return modelDescriptions.value[modelKey] || '暂无模型简介'
}

// 点击查看模型详情
const viewModelDetails = (modelKey: string) => {
  ElMessage.info(`查看 ${getModelDisplayName(modelKey, aiModels.value)} 的详细模型信息`)
}

// 模型详细信息数据
const modelDetails = ref<{ [key: string]: any }>({
  'Grok-4': {
    rank: 15,
    flowers: 8,
    eggs: 2,
    popularity: 12543,
    discussions: 12,
    ratings: {
      responseSpeed: { score: 4.2, stars: 4 },
      accuracy: { score: 4.5, stars: 4 },
      copywriting: { score: 4.0, stars: 4 },
      drawing: { score: 3.8, stars: 4 },
      programming: { score: 4.3, stars: 4 }
    }
  },
  'AskAgents': {
    rank: 28,
    flowers: 5,
    eggs: 1,
    popularity: 8921,
    discussions: 8,
    ratings: {
      responseSpeed: { score: 3.8, stars: 4 },
      accuracy: { score: 4.2, stars: 4 },
      copywriting: { score: 3.6, stars: 4 },
      drawing: { score: 2.8, stars: 3 },
      programming: { score: 4.0, stars: 4 }
    }
  },
  'deepseek-reasoner': {
    rank: 12,
    flowers: 15,
    eggs: 3,
    popularity: 18765,
    discussions: 25,
    ratings: {
      responseSpeed: { score: 3.5, stars: 3 },
      accuracy: { score: 4.8, stars: 5 },
      copywriting: { score: 4.2, stars: 4 },
      drawing: { score: 2.5, stars: 2 },
      programming: { score: 4.6, stars: 5 }
    }
  },
  'Gemini-2.5-Flash': {
    rank: 8,
    flowers: 22,
    eggs: 4,
    popularity: 23456,
    discussions: 18,
    ratings: {
      responseSpeed: { score: 4.8, stars: 5 },
      accuracy: { score: 4.3, stars: 4 },
      copywriting: { score: 4.1, stars: 4 },
      drawing: { score: 3.9, stars: 4 },
      programming: { score: 4.0, stars: 4 }
    }
  },
  'DeepSeek-R1_Internet': {
    rank: 18,
    flowers: 12,
    eggs: 2,
    popularity: 15678,
    discussions: 15,
    ratings: {
      responseSpeed: { score: 3.8, stars: 4 },
      accuracy: { score: 4.6, stars: 5 },
      copywriting: { score: 4.0, stars: 4 },
      drawing: { score: 2.8, stars: 3 },
      programming: { score: 4.4, stars: 4}
    },
  },
  'GPT-4.1-nano': {
    rank: 25,
    flowers: 6,
    eggs: 1,
    popularity: 9876,
    discussions: 9,
    ratings: {
      responseSpeed: { score: 4.5, stars: 4 },
      accuracy: { score: 4.0, stars: 4 },
      copywriting: { score: 3.8, stars: 4 },
      drawing: { score: 3.2, stars: 3 },
      programming: { score: 3.9, stars: 4 }
    }
  },
  'Fudian-Searh': {
    rank: 35,
    flowers: 4,
    eggs: 3,
    popularity: 6543,
    discussions: 6,
    ratings: {
      responseSpeed: { score: 3.2, stars: 3 },
      accuracy: { score: 3.8, stars: 4 },
      copywriting: { score: 3.4, stars: 3 },
      drawing: { score: 2.0, stars: 2 },
      programming: { score: 3.6, stars: 4 }
    }
  },
  'Gemini-2.5-Pro-youhui': {
    rank: 20,
    flowers: 18,
    eggs: 2,
    popularity: 14567,
    discussions: 14,
    ratings: {
      responseSpeed: { score: 4.0, stars: 4 },
      accuracy: { score: 4.4, stars: 4 },
      copywriting: { score: 4.2, stars: 4 },
      drawing: { score: 3.8, stars: 4 },
      programming: { score: 4.1, stars: 4 }
    }
  },
  'Gemini-2.5-Pro': {
    rank: 6,
    flowers: 35,
    eggs: 5,
    popularity: 28765,
    discussions: 32,
    ratings: {
      responseSpeed: { score: 4.2, stars: 4 },
      accuracy: { score: 4.7, stars: 5 },
      copywriting: { score: 4.5, stars: 4 },
      drawing: { score: 4.3, stars: 4 },
      programming: { score: 4.4, stars: 4 }
    }
  },
  'gpt-4.1': {
    rank: 3,
    flowers: 45,
    eggs: 8,
    popularity: 35678,
    discussions: 42,
    ratings: {
      responseSpeed: { score: 4.0, stars: 4 },
      accuracy: { score: 4.8, stars: 5 },
      copywriting: { score: 4.6, stars: 5 },
      drawing: { score: 4.1, stars: 4 },
      programming: { score: 4.7, stars: 5 }
    }
  },
  'doubao-1.5-Pro': {
    rank: 22,
    flowers: 9,
    eggs: 2,
    popularity: 12345,
    discussions: 11,
    ratings: {
      responseSpeed: { score: 4.1, stars: 4 },
      accuracy: { score: 4.2, stars: 4 },
      copywriting: { score: 4.3, stars: 4 },
      drawing: { score: 3.5, stars: 4 },
      programming: { score: 3.8, stars: 4 }
    }
  },
  'deepseek-chat': {
    rank: 16,
    flowers: 11,
    eggs: 3,
    popularity: 13456,
    discussions: 13,
    ratings: {
      responseSpeed: { score: 4.3, stars: 4 },
      accuracy: { score: 4.4, stars: 4 },
      copywriting: { score: 4.0, stars: 4 },
      drawing: { score: 3.0, stars: 3 },
      programming: { score: 4.2, stars: 4 }
    }
  },
  'claude-4-sonnet': {
    rank: 9,
    flowers: 28,
    eggs: 4,
    popularity: 19876,
    discussions: 21,
    ratings: {
      responseSpeed: { score: 3.9, stars: 4 },
      accuracy: { score: 4.6, stars: 5 },
      copywriting: { score: 4.4, stars: 4 },
      drawing: { score: 3.8, stars: 4 },
      programming: { score: 4.3, stars: 4 }
    }
  }
})

// 获取模型详细信息
const getModelDetails = (modelKey: string) => {
  const model = aiModels.value.find(m => m.modelKey === modelKey)
  if (model) {
    return {
      rank: model.rankPosition || 0,
      flowers: model.flowersCount || 0,
      eggs: model.eggsCount || 0,
      popularity: model.popularityScore || 0,
      discussions: model.discussionsCount || 0,
      ratings: {
        responseSpeed: { score: model.responseSpeedScore || 0, stars: Math.round(model.responseSpeedScore || 0) },
        accuracy: { score: model.accuracyScore || 0, stars: Math.round(model.accuracyScore || 0) },
        copywriting: { score: model.copywritingScore || 0, stars: Math.round(model.copywritingScore || 0) },
        drawing: { score: model.drawingScore || 0, stars: Math.round(model.drawingScore || 0) },
        programming: { score: model.programmingScore || 0, stars: Math.round(model.programmingScore || 0) }
      }
    }
  }
  return modelDetails.value[modelKey] || {
    rank: 50,
    flowers: 0,
    eggs: 0,
    popularity: 1000,
    discussions: 0,
    ratings: {
      responseSpeed: { score: 3.0, stars: 3 },
      accuracy: { score: 3.0, stars: 3 },
      copywriting: { score: 3.0, stars: 3 },
      drawing: { score: 3.0, stars: 3 },
      programming: { score: 3.0, stars: 3 }
    }
  }
}

// 悬停状态管理
const hoveredModelId = ref<number | null>(null)
const hoverTimeout = ref<NodeJS.Timeout | null>(null)

const handleMouseEnter = (modelId: number) => {
  if (hoverTimeout.value) {
    clearTimeout(hoverTimeout.value)
    hoverTimeout.value = null
  }
  hoveredModelId.value = modelId
}

const handleMouseLeave = (modelId: number) => {
  hoverTimeout.value = setTimeout(() => {
    hoveredModelId.value = null
  }, 200)
}

const handlePopupMouseEnter = () => {
  if (hoverTimeout.value) {
    clearTimeout(hoverTimeout.value)
    hoverTimeout.value = null
  }
}

const handlePopupMouseLeave = () => {
  hoveredModelId.value = null
}

const isModelHovered = (modelId: number) => {
  return hoveredModelId.value === modelId
}

// 按钮事件处理
const handleMicrophone = () => {
  ElMessage.info('语音功能开发中...')
}

const handleUpload = () => {
  ElMessage.info('上传功能开发中...')
}

// 组件挂载时获取AI模型数据
onMounted(() => {
  fetchAiModels()
})
</script>

<style scoped>
/* 确保页面内容可以超出视窗，触发滚动条 */
:global(html) {
  overflow-y: auto;
}

:global(body) {
  overflow-y: auto;
  margin: 0;
  padding: 0;
}

/* 文本截断样式 */
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}

/* 工具提示样式优化 */
.group:hover .group-hover\:opacity-100 {
opacity: 1;
}

/* 星级评分样式 */
.fa-star, .fa-star-half-alt {
font-size: 12px;
margin-right: 2px;
}

/* 确保 TailwindCSS 样式优先级 */
</style>